package com.axialproject.health.exchange.bp.healthvaultppe;

import com.axialproject.health.exchange.EMF;
import com.axialproject.health.exchange.PatientManager;
import com.axialproject.health.exchange.entity.Patient;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class RegisterServlet extends HttpServlet {

    private static final Logger log = Logger.getLogger(RegisterServlet.class.getName());

    public void doPost (HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

        String appUrl = this.getServletContext().getInitParameter("AppUrl");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        
        if (username == null || "".equals(username)) {
            resp.setContentType("text/html");
            resp.getWriter().println("Must have username");
            return;
        }
        
        if (password == null || "".equals(password)) {
            resp.setContentType("text/html");
            resp.getWriter().println("Please provide a password");
            return;
        }

        EntityManager em = EMF.get().createEntityManager();
        try {
            Patient patient = PatientManager.getPatientByUsernameAppName(em, username, "bp");
            if (patient == null) {
                patient = new Patient ();
                patient.setUsername(username);
                patient.setPassword (password);
                patient.setAppName("bp");
                PatientManager.savePatient(em, patient);
            } else {
                if (!password.equals(patient.getPassword())) {
                    resp.sendRedirect(appUrl + "/bp/healthvaultppe/register.jsp?username=" + username);
                    return;
                }
            }

        
        } catch (Exception e) {
            log.log (Level.SEVERE, e.getMessage(), e);
            resp.setContentType("text/html");
            resp.getWriter().println("Network error when accessing the exchange");
        } finally {
            em.close ();
        }

        resp.sendRedirect(appUrl + "/healthvaultppe/create_login?appName=bp&username=" + username + "&redirectUrl=" +
            appUrl + "/bp/healthvaultppe/register_link.jsp&finishUrl=" +
            appUrl + "/bp/healthvaultppe/register_done.jsp");
    }

    public void doGet (HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        doPost (req, resp);
    }
}
